package com.cccccc.service.impl;

import com.cccccc.mapper.user.UserMapper;
import com.cccccc.object.User;
import com.cccccc.object.UserIut;
import com.cccccc.service.UserService;
import com.cccccc.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/8/18
 * 备注：用户业务层实现类
 */
@Slf4j
@Service // 业务层注解
public class UserServiceImpl implements UserService {
    // 自动注入
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(String username, String password) {
        Authentication authenticate = null;
        try {
            // 创建一个UsernamePasswordAuthenticationToken对象，用于验证用户名和密码
            authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("用户名或密码错误");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
        // 验证成功后，获取用户信息
        // 定义存储到Token的数据
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        // 获取权限
        Collection<? extends GrantedAuthority> authorities = authenticate.getAuthorities();
        // 将权限存入Set集合
        Set<String> authoritySet = new HashSet<>();
        authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        claims.put("perms", authoritySet);
        // 生成Token
        String token = jwtUtils.createToken(claims);
        return token;

    }

    @Override
    public void quit() {
        log.info("清除Token");
        // 退出登录，清除Token
        SecurityContextHolder.clearContext();
    }

    @Override
    public List<User> selectUser(UserIut userIut) {
        return userMapper.selectUser(userIut);
    }

    @Override
    public int deleteUser(Integer id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public int deleteUsers(List<Integer> ids) {
        return userMapper.deleteUsers(ids);
    }

    @Override
    public int addUser(User user) {
        log.info("添加用户: {}", user);
        // 密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 加密
        String encode = passwordEncoder.encode(user.getPassword());
        log.info("加密后的密码: {}", encode);
        user.setPassword(encode);
        // 获取当前时间
        Date date = new Date();
        log.info("当前时间: {}", date);
        user.setTime(date);
        return userMapper.addUser(user);
    }

    @Override
    public int updataUser(User user) {
        return userMapper.updataUser(user);
    }
}
